package com.xhcl.system.service.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xhcl.common.core.text.Convert;
import com.xhcl.common.utils.http.HttpUtils;
import com.xhcl.system.domain.TGgSjtb;
import com.xhcl.system.mapper.TGgSjtbMapper;
import com.xhcl.system.model.DwModel;
import com.xhcl.system.model.RespModel;
import com.xhcl.system.model.WlZhModel;
import com.xhcl.system.model.WlZhtiModel;
import com.xhcl.system.model.XmModel;
import com.xhcl.system.model.YskmModel;
import com.xhcl.system.model.ZhModel;
import com.xhcl.system.model.ZhtiModel;
import com.xhcl.system.service.ITGgSjtbService;
import com.xhcl.system.service.ITSrhsHsxtcsService;

/**
 * 数据同步Service业务层处理
 * 
 * @author xhcl
 * @date 2020-09-02
 */
@Service
public class TGgSjtbServiceImpl implements ITGgSjtbService 
{
    @Autowired
    private TGgSjtbMapper tGgSjtbMapper;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private ITSrhsHsxtcsService tSrhsHsxtcsService;
    
    private static final Log logger = LogFactory.getLog(TGgSjtbServiceImpl.class);

    /**
     * 查询数据同步
     * 
     * @param lsh 数据同步ID
     * @return 数据同步
     */
    @Override
    public TGgSjtb selectTGgSjtbById(String lsh)
    {
        return tGgSjtbMapper.selectTGgSjtbById(lsh);
    }

    /**
     * 查询数据同步列表
     * 
     * @param tGgSjtb 数据同步
     * @return 数据同步
     */
    @Override
    public List<TGgSjtb> selectTGgSjtbList(TGgSjtb tGgSjtb)
    {
        return tGgSjtbMapper.selectTGgSjtbList(tGgSjtb);
    }

    /**
     * 新增数据同步
     * 
     * @param tGgSjtb 数据同步
     * @return 结果
     */
    @Override
    public int insertTGgSjtb(TGgSjtb tGgSjtb)
    {
        return tGgSjtbMapper.insertTGgSjtb(tGgSjtb);
    }

    /**
     * 修改数据同步
     * 
     * @param tGgSjtb 数据同步
     * @return 结果
     */
    @Override
    public int updateTGgSjtb(TGgSjtb tGgSjtb)
    {
        return tGgSjtbMapper.updateTGgSjtb(tGgSjtb);
    }

    /**
     * 删除数据同步对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTGgSjtbByIds(String ids)
    {
        return tGgSjtbMapper.deleteTGgSjtbByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除数据同步信息
     * 
     * @param lsh 数据同步ID
     * @return 结果
     */
    @Override
    public int deleteTGgSjtbById(String lsh)
    {
        return tGgSjtbMapper.deleteTGgSjtbById(lsh);
    }
   
    public void syncBaseData()
    {
      try {
        List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from t_gg_sjtb o where tblx in('dw','xm','yskm')  order by o.tblx desc");

        if ((list == null) || (list.size() == 0)) {
          logger.info("请先设置要同步的基础配置信息");
          return;
        }
        String qh = tSrhsHsxtcsService.getHsxtcsnr("bjczqh");  
        if (StringUtils.isEmpty(qh)) {
          logger.info("本级财政区划为空");
          return;
        }
        for (Map map : list) {
          String tblsh = map.get("LSH").toString();
          String tblx = map.get("TBLX").toString();
          String tblxmc = map.get("TBLXMC").toString();
          String tbUrl = map.get("TBURL").toString();
          String reqtbUrl = tbUrl + "/" + qh;
          if ((StringUtils.isNotEmpty(tblx)) && (StringUtils.isNotEmpty(tbUrl))) {
            if (tblx.equals("dw")) {
              dwload(tblsh, reqtbUrl);
            }
            else if (tblx.equals("xm"))
              xmload(tblsh, reqtbUrl);
            else if (tblx.equals("yskm")) {
              yskmload(tblsh, reqtbUrl);
            }
          }
        }
      }
      catch (Exception e)
      {
        logger.info("同步出错" + e.getMessage());
        throw e;
      }
    }
    @Transactional
    public void synYwData() {
      try {
      	List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from t_gg_sjtb o where tblx in('accept')  order by o.tblx desc");

        if ((list == null) || (list.size() == 0)) {
          logger.info("请先设置要同步的基础配置信息");
          return;
        }
        String qh = tSrhsHsxtcsService.getHsxtcsnr("bjczqh");
        if (StringUtils.isEmpty(qh)) {
          logger.info("本级财政区划为空");
          return;
        }
        for (Map map : list) {
          String tblsh = map.get("LSH").toString();
          String tblx = map.get("TBLX").toString();
          String tblxmc = map.get("TBLXMC").toString();
          String tbUrl = map.get("TBURL").toString();
          String reqtbUrl = tbUrl + "/" + qh;
          if ((StringUtils.isNotEmpty(tblx)) && (StringUtils.isNotEmpty(tbUrl)) && 
            (tblx.equals("accept"))) {
            acceptload(tblsh, "", reqtbUrl);
          }
        }

      }
      catch (Exception e)
      {
        logger.info("同步出错" + e.getMessage());
        throw e;
      }
    }

    public void sync(String lsh, String syncdate)
    {
      try {
        List<Map<String,Object>> list = null;
        if (StringUtils.isNotEmpty(lsh)) {
          Object[] params = { lsh };
          list = jdbcTemplate.queryForList("select * from t_gg_sjtb o where o.lsh = ? order by o.tblx desc", 
            params);
        } else {
          list = jdbcTemplate.queryForList("select * from t_gg_sjtb o order by o.tblx desc");
        }
        if ((list == null) || (list.size() == 0)) {
          logger.info("请先设置要同步的基础配置信息");
          return;
        }

        String qh = tSrhsHsxtcsService.getHsxtcsnr("bjczqh");
        if (StringUtils.isEmpty(qh)) {
          logger.info("本级财政区划为空");
          return;
        }
        for (Map map : list) {
          String tblsh = map.get("LSH").toString();
          String tblx = map.get("TBLX").toString();
          String tblxmc = map.get("TBLXMC").toString();
          String tbUrl = map.get("TBURL").toString();
          String reqtbUrl = tbUrl + "/" + qh;
          if ((StringUtils.isNotEmpty(tblx)) && (StringUtils.isNotEmpty(tbUrl))) {
            if (tblx.equals("dw")) {
              dwload(tblsh, reqtbUrl);
            }
            else if (tblx.equals("xm"))
              xmload(tblsh, reqtbUrl);
            else if (tblx.equals("yskm"))
              yskmload(tblsh, reqtbUrl);
            else if (tblx.equals("accept")) {
              acceptload(tblsh, syncdate, reqtbUrl);
            }
            else if (tblx.equals("wlaccept")) {
                wlacceptload(tblsh, syncdate, reqtbUrl);
              }
          }
        }
      }
      catch (Exception e)
      {
        logger.info("同步出错" + e.getMessage());
        throw e;
      }
    }

    private void dwload(String tblsh, String tbUrl) { logger.info("开始同步非税单位请求地址:" + tbUrl);
      jdbcTemplate.update("update t_gg_sjtb set tbqssj=? where lsh=?", new Object[] { new java.util.Date(), tblsh });
      String respStr = HttpUtils.sendPostJson(tbUrl, "");
      if (StringUtils.isNotEmpty(respStr)) {
        RespModel rsp = (RespModel)JSON.parseObject(respStr, RespModel.class);
        if (rsp.getCode().equals("0")) {
          String listjson = rsp.getResult();
          List dwlist = JSONArray.parseArray(listjson, DwModel.class);
          logger.info("单位转成对像后的json" + JSON.toJSONString(dwlist));
          SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
          String delsql = "delete from T_GG_FSDW_TEMP";
          jdbcTemplate.execute(delsql);
          BatchPreparedStatementSetter setter = null;
          String sql = "insert into T_GG_FSDW_TEMP(DWBM,DWMC,DWDZ,DWLXR,DWLXDH,SFMJ,JC,JBR,JBSJ,BZ,SJDWBM,QYBZ,YXBZ) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
          final List list = dwlist;
          setter = new BatchPreparedStatementSetter() {
            public int getBatchSize() {
              return list.size();
            }

            public void setValues(PreparedStatement ps, int index) throws SQLException {
              DwModel dw = (DwModel)list.get(index);
              ps.setString(1, dw.getDwbm());
              ps.setString(2, dw.getDwmc());
              ps.setString(3, dw.getDwdz());
              ps.setString(4, dw.getDwlxr());
              ps.setString(5, dw.getDwlxdh());
              ps.setInt(6, dw.getSfmj());
              ps.setInt(7, dw.getJc());
              ps.setString(8, dw.getJbr());
              ps.setDate(9, new java.sql.Date(new java.util.Date().getTime()));
              ps.setString(10, dw.getBz());
              ps.setString(11, dw.getSjdwbm());
              ps.setString(12, dw.getQybz());
              ps.setString(13, dw.getYxbz());
            }
          };
          jdbcTemplate.batchUpdate(sql, setter);
          String updatesql = "insert into  T_GG_FSDW(DWBM,DWMC,DWDZ,DWLXR,DWLXDH,SFMJ,JC,JBR,JBSJ,BZ,SJDWBM)   select DWBM,DWMC,DWDZ,DWLXR,DWLXDH,SFMJ,JC,JBR,JBSJ,BZ,SJDWBM from T_GG_FSDW_TEMP a where QYBZ='1' and YXBZ='1' and  not exists(select 0 from T_GG_FSDW b where a.DWBM=b.DWBM)";

          jdbcTemplate.execute(updatesql);
          jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='1',code=?,MSG=?,TALCOUNT=? where lsh=?", new Object[] { new java.util.Date(), rsp.getCode(), "同步成功", Integer.valueOf(dwlist.size()), tblsh });
        } else {
          jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',code=?,msg=? where lsh=?", new Object[] { new java.util.Date(), rsp.getCode(), rsp.getMsg(), tblsh });
        }
      } else {
        jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',ERRMSG=? where lsh=?", new Object[] { new java.util.Date(), "请求服务出错，返回内容为空!", tblsh });
      }
      logger.info("结束同步非税单位请求地址:" + tbUrl); }

    private void xmload(String tblsh, String tbUrl)
    {
      logger.info("开始同步项目请求地址:" + tbUrl);
      jdbcTemplate.update("update t_gg_sjtb set tbqssj=? where lsh=?", new Object[] { new java.util.Date(), tblsh });
      String respStr = HttpUtils.sendPostJson(tbUrl, "");
      if (StringUtils.isNotEmpty(respStr)) {
        RespModel rsp = (RespModel)JSON.parseObject(respStr, RespModel.class);
        if (rsp.getCode().equals("0")) {
          String listjson = rsp.getResult();
          List dwlist = JSONArray.parseArray(listjson, XmModel.class);
          logger.info("项目转成对像后的json" + JSON.toJSONString(dwlist));
          String delsql = "delete from t_gg_xmxx";
          jdbcTemplate.execute(delsql);
          BatchPreparedStatementSetter setter = null;
          String sql = "insert into t_gg_xmxx(XMBM,XMMC,JLDW,SRLBBM,SRLBMC,YSKMBM,YSKMMC,SFSX,SFXX,QSSJ,ZZSJ,GLLX,XMCJ,SFDJ,FCBZ,FCJS,FCTSBZ,ZYFC,SEJFC,SIJFC,XJFC,SJXMBM,QYBZ,YXBZ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
          final List list = dwlist;
          setter = new BatchPreparedStatementSetter() {
            public int getBatchSize() {
              return list.size();
            }

            public void setValues(PreparedStatement ps, int index) throws SQLException {
              XmModel xm = (XmModel)list.get(index);
              ps.setString(1, xm.getXmbm());
              ps.setString(2, xm.getXmmc());
              ps.setString(3, xm.getJldw());
              ps.setString(4, xm.getSrlbbm());
              ps.setString(5, xm.getSrlbmc());
              ps.setString(6, xm.getYskmbm());
              ps.setString(7, xm.getYskmmc());
              ps.setBigDecimal(8, xm.getSfsx());
              ps.setBigDecimal(9, xm.getSfsx());
              ps.setString(10, xm.getQssj());
              ps.setString(11, xm.getZzsj());
              ps.setString(12, xm.getGllx());
              ps.setInt(13, xm.getXmcj());
              ps.setInt(14, xm.getSfdj());
              ps.setInt(15, xm.getFcbz());
              ps.setBigDecimal(16, xm.getFcjs());
              ps.setString(17, xm.getFctsbz());
              ps.setBigDecimal(18, xm.getZyfc());
              ps.setBigDecimal(19, xm.getSejfc());
              ps.setBigDecimal(20, xm.getSijfc());
              ps.setBigDecimal(21, xm.getXjfc());
              ps.setString(22, xm.getSjxmbm());
              ps.setString(23, xm.getQybz());
              ps.setString(24, xm.getYxbz());
            }
          };
          jdbcTemplate.batchUpdate(sql, setter);
          jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='1',code=?,MSG=?,TALCOUNT=? where lsh=?", new Object[] { new java.util.Date(), rsp.getCode(), "同步成功", Integer.valueOf(dwlist.size()), tblsh });
        } else {
          jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',code=?,msg=? where lsh=?", new Object[] { new java.util.Date(), rsp.getCode(), rsp.getMsg(), tblsh });
        }
      } else {
        jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',ERRMSG=? where lsh=?", new Object[] { new java.util.Date(), "请求服务出错，返回内容为空!", tblsh });
      }
      logger.info("结束同步项目请求地址:" + tbUrl);
    }
    private void yskmload(String tblsh, String tbUrl) {
      logger.info("开始同步预算科目请求地址:" + tbUrl);
      jdbcTemplate.update("update t_gg_sjtb set tbqssj=? where lsh=?", new Object[] { new java.util.Date(), tblsh });
      String respStr = HttpUtils.sendPostJson(tbUrl, "");
      if (StringUtils.isNotEmpty(respStr)) {
        RespModel rsp = (RespModel)JSON.parseObject(respStr, RespModel.class);
        if (rsp.getCode().equals("0")) {
          String listjson = rsp.getResult();
          List dwlist = JSONArray.parseArray(listjson, YskmModel.class);
          logger.info("预算科目转成对像后的json" + JSON.toJSONString(dwlist));
          final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
          String delsql = "delete from t_gg_yskm_temp";
          jdbcTemplate.execute(delsql);
          DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
          BatchPreparedStatementSetter setter = null;
          String sql = "insert into t_gg_yskm_temp(YSKM,YSKMMC,QSSJ,ZZSJ,SJYSKM,JC,SFMJ,KMLB,BZ,QYBZ,YXBZ) values (?,?,?,?,?,?,?,?,?,?,?)";
          final List list = dwlist;
          setter = new BatchPreparedStatementSetter() {
            public int getBatchSize() {
              return list.size();
            }

            public void setValues(PreparedStatement ps, int index) throws SQLException
            {
              YskmModel yskm = (YskmModel)list.get(index);
              ps.setString(1, yskm.getYskm());
              ps.setString(2, yskm.getYskmmc());
              try {
                ps.setDate(3, new java.sql.Date(sdf.parse(yskm.getQssj()).getTime()));
              }
              catch (ParseException e) {
                e.printStackTrace();
              }
              ps.setDate(4, null);
              ps.setString(5, yskm.getSjyskm());
              ps.setInt(6, yskm.getJc());
              ps.setInt(7, yskm.getSfmj());
              ps.setString(8, yskm.getKmlb());
              ps.setString(9, yskm.getBz());
              ps.setString(10, yskm.getQybz());
              ps.setString(11, yskm.getYxbz());
            }
          };
          jdbcTemplate.batchUpdate(sql, setter);
          String updatesql = "insert into  t_gg_yskm(YSKM,YSKMMC,QSSJ,ZZSJ,SJYSKM,JC,SFMJ,KMLB,BZ,QYBZ,YXBZ)   select YSKM,YSKMMC,QSSJ,ZZSJ,SJYSKM,JC,SFMJ,KMLB,BZ,QYBZ,YXBZ from t_gg_yskm_temp a where not exists(select 0 from t_gg_yskm b where a.YSKM=b.YSKM)";

          jdbcTemplate.execute(updatesql);
          jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='1',code=?,MSG=?,TALCOUNT=? where lsh=?", new Object[] { new java.util.Date(), rsp.getCode(), "同步成功", Integer.valueOf(dwlist.size()), tblsh });
        } else {
          jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',code=?,msg=? where lsh=?", new Object[] { new java.util.Date(), rsp.getCode(), rsp.getMsg(), tblsh });
        }
      } else {
        jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',ERRMSG=? where lsh=?", new Object[] { new java.util.Date(), "请求服务出错，返回内容为空!", tblsh });
      }
      logger.info("结束同步预算科目请求地址:" + tbUrl);
    }

    private void acceptload(String tblsh, String syncdate, String tbUrl)
    {
      logger.info("开始专户数据请求地址:" + tbUrl);

      if (StringUtils.isEmpty(syncdate)) {
          DateFormat df = new SimpleDateFormat("yyyyMMdd");
  	    Date date = new Date();
  		Calendar calendar = Calendar.getInstance();//new一个Calendar类,把Date放进去
  		calendar.setTime(date);
  		calendar.add(Calendar.DATE, -1);
          syncdate = df.format(calendar.getTime());
      } else {
        syncdate = syncdate.replace("-", "");
      }
      jdbcTemplate.update("update t_gg_sjtb set tbqssj=? where lsh=?", new Object[] { new java.util.Date(), tblsh });
      String respStr = HttpUtils.sendPostJson(tbUrl + "/" + syncdate, "");
      if (StringUtils.isNotEmpty(respStr)) {
        RespModel rsp = (RespModel)JSON.parseObject(respStr, RespModel.class);
        if (rsp.getCode().equals("0")) {
          String listjson = rsp.getResult();
          List<ZhModel> zhlist = JSONArray.parseArray(listjson, ZhModel.class);
          logger.info("专户数据转成对像后的json" + JSON.toJSONString(zhlist));
          BatchPreparedStatementSetter setter = null;
          String sql = "insert into T_SRHS_YHSJJS(LSH,JSN,JSY,JSR,SFJS,JE,SJLY)  select ?,?,?,?,?,?,? from dual where not exists(select lsh from  T_SRHS_YHSJJS a where a.lsh=?)";
          final List list = zhlist;
          setter = new BatchPreparedStatementSetter() {
            public int getBatchSize() {
              return list.size();
            }

            public void setValues(PreparedStatement ps, int index) throws SQLException {
              ZhModel zh = (ZhModel)list.get(index);
              ps.setLong(1, zh.getPch().longValue());
              ps.setString(2, zh.getSenddate().substring(0, 4));
              ps.setString(3, zh.getSenddate().substring(4, 6));
              ps.setString(4, zh.getSenddate().substring(6, 8));
              ps.setString(5, "0");
              ps.setBigDecimal(6, zh.getIncome());
              ps.setInt(7, 1);
              ps.setLong(8, zh.getPch().longValue());
            }
          };
          jdbcTemplate.batchUpdate(sql, setter);

          final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
          String jkssql = "insert into T_SRHS_INCOMEJKS(LSH,INCOME,REMARK,RECEIVE_DATE,YHBM,YHMC,YHZH,SEND_DATE,PJH) select ?,?,?,?,?,?,?,?,? from dual where not exists(select lsh from T_SRHS_INCOMEJKS a where a.lsh=?)";
          final List jkslist = zhlist;
          setter = new BatchPreparedStatementSetter() {
            public int getBatchSize() {
              return jkslist.size();
            }

            public void setValues(PreparedStatement ps, int index) throws SQLException {
              ZhModel zh = (ZhModel)jkslist.get(index);
              ps.setLong(1, zh.getPch().longValue());
              ps.setBigDecimal(2, zh.getIncome());
              ps.setString(3, zh.getRemark());
              try {
                ps.setDate(4, new java.sql.Date(sdf.parse(zh.getSenddate()).getTime()));
              }
              catch (ParseException e1) {
                e1.printStackTrace();
              }
              ps.setString(5, zh.getZhyhbm());
              ps.setString(6, zh.getZhyhmc());
              ps.setString(7, zh.getZhyhzh());
              try {
                ps.setDate(8, new java.sql.Date(sdf.parse(zh.getSenddate()).getTime()));
              }
              catch (ParseException e) {
                e.printStackTrace();
              }
              ps.setString(9, zh.getPjh());
              ps.setLong(10, zh.getPch().longValue());
            }
          };
          jdbcTemplate.batchUpdate(jkssql, setter);
          

          //更新银行编号
          
          String updatejkssql = "update T_SRHS_INCOMEJKS a set yhbm=(select max(yhbm) from T_GG_DLYHWH b where a.yhzh=b.SKRZH) where a.lsh=? and exists(select 0 from T_GG_DLYHWH b where a.yhzh=b.SKRZH)";
          final List upjkslist = zhlist;
          setter = new BatchPreparedStatementSetter() {
            public int getBatchSize() {
              return upjkslist.size();
            }

            public void setValues(PreparedStatement ps, int index) throws SQLException {
              ZhModel zh = (ZhModel)upjkslist.get(index);
              ps.setLong(1, zh.getPch().longValue());
            }
          };
          jdbcTemplate.batchUpdate(updatejkssql, setter);
          
          
          List alist = new ArrayList();
          for (ZhModel zh : zhlist) {
            alist.add(String.valueOf(zh.getPch()));
          }
          List<String> onelist = removeDuplicate(alist);
          for (String pjh : onelist) {
            jdbcTemplate.update("delete from T_SRHS_INCOMEMX where lsh=?", new Object[] { pjh });
          }
          for (ZhModel zh : zhlist) {
            String tiJson = zh.getZhtilist();
            List zhtilist = JSONArray.parseArray(tiJson, ZhtiModel.class);
            String tisql = "insert into T_SRHS_INCOMEMX(LSH,DWBM,DWMC,INCOME,YSKM,YSKMMC,XMBM,XMMC,RECEIVE_DATE,SEND_DATE)values( ?,?,?,?,?,?,?,?,?,?)";
            final List tilist = zhtilist;
            setter = new BatchPreparedStatementSetter() {
              public int getBatchSize() {
                return tilist.size();
              }

              public void setValues(PreparedStatement ps, int index) throws SQLException {
                ZhtiModel zh = (ZhtiModel)tilist.get(index);
                ps.setLong(1, zh.getPch().longValue());
                ps.setString(2, zh.getDwbm());
                ps.setString(3, zh.getDwmc());
                ps.setBigDecimal(4, zh.getIncome());
                ps.setString(5, zh.getYskm());
                ps.setString(6, zh.getYskmmc());
                ps.setString(7, zh.getXmbm());
                ps.setString(8, zh.getXmmc());
                try {
                  ps.setDate(9, new java.sql.Date(sdf.parse(zh.getSenddate()).getTime()));
                }
                catch (ParseException e) {
                  e.printStackTrace();
                }
                try {
                  ps.setDate(10, new java.sql.Date(sdf.parse(zh.getSenddate()).getTime()));
                }
                catch (ParseException e) {
                  e.printStackTrace();
                }
              }
            };
            jdbcTemplate.batchUpdate(tisql, setter);
          }

          jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='1',code=?,MSG=?,TALCOUNT=? where lsh=?", new Object[] { new java.util.Date(), rsp.getCode(), "同步成功", Integer.valueOf(list.size()), tblsh });
        } else {
          jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',code=?,msg=? where lsh=?", new Object[] { new java.util.Date(), rsp.getCode(), rsp.getMsg(), tblsh });
        }
      } else {
        jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',ERRMSG=? where lsh=?", new Object[] { new java.util.Date(), "请求服务出错，返回内容为空!", tblsh });
      }
      logger.info("结束专户数据请求地址:" + tbUrl);
    }
    
    public List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
      }
      
    private  void wlacceptload(String tblsh,String syncdate,String tbUrl){
    		  logger.info("开始专户往来数据请求地址:"+tbUrl);
    		  
    		  if (StringUtils.isEmpty(syncdate)){
    			  java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyyMMdd");
    			  syncdate= format1.format(new Date());
    		  }else {
    			  syncdate=syncdate.replace("-", "");
    		  }
    		  jdbcTemplate.update("update t_gg_sjtb set tbqssj=? where lsh=?",  new Object[] {new Date(),tblsh});
    		  String respStr=HttpUtils.sendPostJson(tbUrl+"/"+syncdate,"");
    		  if (StringUtils.isNotEmpty(respStr)){
    			  RespModel rsp=JSON.parseObject(respStr, RespModel.class);
    			  if (rsp.getCode().equals("0")){
    				  String listjson=rsp.getResult();
    				  List<WlZhModel> zhlist=JSONArray.parseArray(listjson, WlZhModel.class);
    				  logger.info("专户往来数据转成对像后的json"+JSON.toJSONString(zhlist));
    				  BatchPreparedStatementSetter setter = null;
    				  String sql = "insert into T_SRHS_YHSJJS(LSH,JSN,JSY,JSR,SFJS,JE,SJLY)  select ?,?,?,?,?,?,? from dual where not exists(select lsh from  T_SRHS_YHSJJS a where a.lsh=?)";
    				  final List list = zhlist;
    				     setter = new BatchPreparedStatementSetter() {
    				      public int getBatchSize() {
    				        return list.size();
    				      }
    				      public void setValues(PreparedStatement ps, int index) throws SQLException
    				      {
    				    	WlZhModel zh = (WlZhModel)list.get(index);
    				    	ps.setLong(1, zh.getPch());
    				        ps.setString(2, zh.getSkrq().substring(0, 4));
    				        ps.setString(3, zh.getSkrq().substring(4, 6));
    				        ps.setString(4, zh.getSkrq().substring(6, 8));
    				        ps.setString(5, "0");
    				        ps.setBigDecimal(6, zh.getIncome());
    				        ps.setInt(7, 1); 
    				        ps.setLong(8, zh.getPch());
    				      }
    				    };
    				    jdbcTemplate.batchUpdate(sql, setter);
    				    
    				    final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    				    String jkssql = "insert into T_SRHS_INCOMEJKS(LSH,INCOME,REMARK,RECEIVE_DATE,YHBM,YHMC,YHZH,SEND_DATE,PJH) select ?,?,?,?,?,?,?,?,? from dual where not exists(select lsh from T_SRHS_INCOMEJKS a where a.lsh=?)";
    					  final List jkslist = zhlist;
    					     setter = new BatchPreparedStatementSetter() {
    					      public int getBatchSize() {
    					        return jkslist.size();
    					      }
    					      public void setValues(PreparedStatement ps, int index) throws SQLException
    					      {
    					    	WlZhModel zh = (WlZhModel)jkslist.get(index);
    					        ps.setLong(1, zh.getPch());
    					        ps.setBigDecimal(2,  zh.getIncome());
    					        ps.setString(3, zh.getRemark());
    					        try {
    								ps.setDate(4, new java.sql.Date((sdf.parse(zh.getSkrq())).getTime()));
    							} catch (ParseException e1) {
    								// TODO Auto-generated catch block
    								e1.printStackTrace();
    							}
    					        ps.setString(5, zh.getSkyhbm());
    					        ps.setString(6, zh.getSkyhmc());
    					        ps.setString(7, zh.getSkzh());
    					        try {
    								ps.setDate(8, new java.sql.Date((sdf.parse(zh.getSkrq())).getTime()));
    							} catch (ParseException e) {
    								// TODO Auto-generated catch block
    								e.printStackTrace();
    							}
    					        ps.setString(9, "");
    					        ps.setLong(10, zh.getPch());
    					      }
    					    };
    					    jdbcTemplate.batchUpdate(jkssql, setter);
    					    logger.info("专户往来更新银行信息成功!");
    					    //更新银行编号
    				        
    				        String updatejkssql = "update T_SRHS_INCOMEJKS a set yhbm=(select max(yhbm) from T_GG_DLYHWH b where a.yhzh=b.SKRZH) where a.lsh=? and exists(select 0 from T_GG_DLYHWH b where a.yhzh=b.SKRZH)";
    				        final List upjkslist = zhlist;
    				        setter = new BatchPreparedStatementSetter() {
    				          public int getBatchSize() {
    				            return upjkslist.size();
    				          }

    				          public void setValues(PreparedStatement ps, int index) throws SQLException {
    				        	WlZhModel zh = (WlZhModel)upjkslist.get(index);
    				            ps.setLong(1, zh.getPch().longValue());
    				          }
    				        };
    				        jdbcTemplate.batchUpdate(updatejkssql, setter);
    				        
    					    
    					    
    					    
    					    List alist = new ArrayList();
    				        for (WlZhModel zh : zhlist) {
    				          alist.add(String.valueOf(zh.getPch()));
    				        }
    				        List<String> onelist = removeDuplicate(alist);
    				        for (String lsh : onelist) {
    				          jdbcTemplate.update("delete from T_SRHS_INCOMEMX where lsh=?", new Object[] { lsh });
    				        }
    					    
    					    for (WlZhModel zhto:zhlist){
    					    	String tiJson=zhto.getZhtilist();
    					    	List<WlZhtiModel> zhtilist=JSONArray.parseArray(tiJson, WlZhtiModel.class);
    					    	String tisql = "insert into T_SRHS_INCOMEMX(LSH,DWBM,DWMC,INCOME,YSKM,YSKMMC,XMBM,XMMC,RECEIVE_DATE,SEND_DATE,JKM,JKR,JKYHZH,JKYHMC,ptpch) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    							final List tilist = zhtilist;
    						     setter = new BatchPreparedStatementSetter() {
    						      public int getBatchSize() {
    						        return tilist.size();
    						      }
    						      public void setValues(PreparedStatement ps, int index) throws SQLException
    						      {
    						    	WlZhtiModel zh = (WlZhtiModel)tilist.get(index);
    						        ps.setLong(1, zh.getPch());
    						        ps.setString(2, zh.getDwbm());
    						        ps.setString(3, zh.getDwmc());
    						        ps.setBigDecimal(4,  zh.getIncome());
    						        ps.setString(5, zh.getYskm());
    						        ps.setString(6, zh.getYskmmc());
    						        ps.setString(7, zh.getXmbm());
    						        ps.setString(8, zh.getXmmc());
    						        try {
    									ps.setDate(9, new java.sql.Date((sdf.parse(zhto.getSkrq())).getTime()));
    								} catch (ParseException e) {
    									// TODO Auto-generated catch block
    									e.printStackTrace();
    								}
    						        try {
    									ps.setDate(10, new java.sql.Date((sdf.parse(zhto.getSkrq())).getTime()));
    								} catch (ParseException e) {
    									// TODO Auto-generated catch block
    									e.printStackTrace();
    								}
    						        ps.setString(11, zh.getJkm());
    						        ps.setString(12, zh.getJkr());
    						        ps.setString(13, zh.getJkyhzh());
    						        ps.setString(14, zh.getJkyhmc());
    						        ps.setString(15, zh.getPtpch());
    						      }
    						    };
    						    jdbcTemplate.batchUpdate(tisql, setter);
    						    	
    					  }
    			        jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='1',code=?,MSG=?,TALCOUNT=? where lsh=?",  new Object[] {new Date(),rsp.getCode(),"同步成功",list.size(),tblsh});
    			  }else{
    				  jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',code=?,msg=? where lsh=?",  new Object[] {new Date(),rsp.getCode(),rsp.getMsg(),tblsh});  
    			  }
    		 }else{
    	         jdbcTemplate.update("update t_gg_sjtb set tbzzsj=?,TBZT='2',ERRMSG=? where lsh=?",  new Object[] {new Date(),"请求服务出错，返回内容为空!",tblsh});
    		  }
    		  logger.info("结束专户往来数据请求地址:"+tbUrl);
    	  }
       
       @Transactional
       public void synYwDataforwl() {
    	    try {
    	    	List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from t_gg_sjtb o where tblx in('wlaccept')  order by o.tblx desc");

    	      if ((list == null) || (list.size() == 0)) {
    	        logger.info("请先设置要同步的基础配置信息");
    	        return;
    	      }
    	      String qh = tSrhsHsxtcsService.getHsxtcsnr("bjczqh");  
    	      if (StringUtils.isEmpty(qh)) {
    	        logger.info("本级财政区划为空");
    	        return;
    	      }
    	      for (Map map : list) {
    	        String tblsh = map.get("LSH").toString();
    	        String tblx = map.get("TBLX").toString();
    	        String tblxmc = map.get("TBLXMC").toString();
    	        String tbUrl = map.get("TBURL").toString();
    	        String reqtbUrl = tbUrl + "/" + qh;
    	        if ((StringUtils.isNotEmpty(tblx)) && (StringUtils.isNotEmpty(tbUrl)) && 
    	          (tblx.equals("wlaccept"))) {
    	          wlacceptload(tblsh, "", reqtbUrl);
    	        }
    	      }

    	    }
    	    catch (Exception e)
    	    {
    	      logger.info("同步出错" + e.getMessage());
    	      throw e;
    	    }
    	  }
}
